#!/usr/bin/env python
# encoding: utf-8
"""
haokan.py

Created by QingFeng on 2008-05-01.
Copyright (c) 2008 QingFeng. All rights reserved.
"""

import urllib,urllib2
import re

def runregx(url,regx):
    """get tuple by regx from html"""
    html=urllib2.urlopen(url).read()
    c=re.compile(regx)
    return c.findall(html)

class HaokanAPI(object):
    """Haokan API"""
    def __init__(self, username):
        super(HaokanAPI, self).__init__()
        self.username = username
        self.storys = {}
        self.images = {}
    def getStorys(self):
        """Find a user storys"""
        url='http://www.haokanbu.com/user/%s/story/?order=ctime'%self.username
        regx=r'<h3><a href="/story/(.*)/">(.*)</a></h3>'
        user_storys=runregx(url,regx)
        for story_id,story_name in user_storys:
            self.storys[story_name]=story_id
        return user_storys
    def getPhotos(self,story_id):
        """Find photos by storyid"""
        url='http://www.haokanbu.com/story/%s/'%story_id
        regx=r'<img id=".*" class="story_photo" src="http://static.haokanbu.com/media/blog/(.*)" alt=".*" />'
        return runregx(url,regx)
    def getImage(self,fname):
        """Get image info"""
        #fname=fname.replace("._","")
        url='http://static.haokanbu.com/media/blog/%s'%fname
        if fname not in self.images:
            local_file,info=urllib.urlretrieve(url)
            print "getImage",local_file
            print "getImage",info
            #buf = open(local_file,'rb').read()
            self.images[fname]={'local_file':local_file}
        else:
            local_file = self.images[fname]['local_file']
            print "local_file",local_file
            #buf=open(local_file,'rb').read()
        return local_file
        #return buf

if __name__ == '__main__':
    username='1605'
    h = HaokanAPI(username)
    for story in h.getStorys():
        print story[0],unicode(story[1],'utf8')
    for img in h.getPhotos('29792'):
        print img
    h.getImage('a336506d3c8146f9a6c65ee917ba929b.png')

